function startServer() {
  const Http = require('http')
  const server = Http.createServer()
  const SocketIo = require('socket.io')
  const io = SocketIo(server)
  const ip = require('ip')

  const { mapToJson } = require('./client/utils')
  function sendMapInfo(clients, myClient) {
    let n = new Map()
    clients.forEach((client, clientKey) => {
      n.set(clientKey, {
        id: clientKey,
        name: Date.now()
      })
    })
    return mapToJson(n)
  }

  function getByValue(map, filter) {
    for (let [key, value] of map.entries()) {
      if (filter(value)){
        return key;
      }
    }
  }

  const clients = new Map()

  function broadcastClients(client) {
    let clientsJson =  sendMapInfo(clients, client)
    client.broadcast.emit('update', clientsJson)
    client.emit('update', clientsJson)
  }

  io.on('connection', client => {
    client.on('keep', data => {
      console.log('live', client.id)
    });
    client.on('conneted', data => {
      console.log('hello', data)
      let clientKey = data ? data : client.id
      clients.set(clientKey, client)
      broadcastClients(client)
      client.emit('myclient', clientKey)
    });
    client.on('file', httpData => {
      console.log('file', httpData)
      if (httpData.clientid && clients.has(httpData.clientid)) {
        let receiveClient = clients.get(httpData.clientid)
        receiveClient.emit('file-send', httpData)
      }
    });
    client.on('disconnect', () => {
      let clientKey = getByValue(clients, function(c) {
        // console.log('disconnect', c)
        return c.id === client.id
      })
      console.log('disconnect', clientKey, client.id)

      if (clientKey) {
        clients.delete(clientKey)
      }
      broadcastClients(client)
    });
  });
  server.listen(3200)
  console.log('------------------------------------');
  console.log(`${ip.address()}:3200`);
  console.log('------------------------------------');
}

module.exports = startServer